﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;

namespace Orchard.Test.Library
{
    public class ListHelper : UIHelperBase
    {
        public ContentItemHelper ContentItemHelper;

        public ListHelper(TestLibrary settings) : base(settings)
        {
            ContentItemHelper = new ContentItemHelper(settings);
        }

        private void InputListSetting(ListSettings listSetting)
        {
            selenium.Type("Routable_Title", listSetting.Title);     
            selenium.Type("Routable_Slug", listSetting.Permalink);
            if (listSetting.SetAsHomePage)
            {
                selenium.Check("Routable_PromoteToHomePage");
            }
            else
            {
                selenium.Uncheck("Routable_PromoteToHomePage");
            }

            if (!String.IsNullOrEmpty(listSetting.ItemContentType))
            {
                selenium.Select("Container_Part_Record_ItemContentType", listSetting.ItemContentType);
            }

            string orderByProperty = listSetting.OrderByProperty == OrderByProperty.DatePublished ? "Date Published" : listSetting.OrderByProperty.ToString();
            selenium.Select("Container_Part_Record_OrderByProperty", String.Format("label={0}", orderByProperty));
            selenium.Select("Container_Part_Record_OrderByDirection", String.Format("label={0}", listSetting.OrderByDirection.ToString()));

            string pageSizeStr = listSetting.PageSize.ToString();
            if (pageSizeStr == "0")
            {
                pageSizeStr = String.Empty;
            }
            selenium.Type("Container_Part_Record_PageSize", pageSizeStr);

            if (listSetting.Paginated)
            {
                selenium.Check("Container_Part_Record_Paginated");
            }
            else
            {
                selenium.Uncheck("Container_Part_Record_Paginated");
            }

            if (listSetting.OnMainMenu)
            {
                selenium.Check("OnMainMenu");
                selenium.Type("MenuText", listSetting.MenuText);
            }
            else
            {
                selenium.Uncheck("OnMainMenu");
            }

            if (listSetting.OnAdminMenu)
            {
                selenium.Check("OnAdminMenu");
                selenium.Type("AdminMenuText", listSetting.AdminMenuText);
                selenium.Type("AdminMenuPosition", listSetting.AdminMenuPosition);
            }
            else
            {
                selenium.Uncheck("OnAdminMenu");
            }

            if (listSetting.Owner != TestLibrary.Consts.AdminUserName)
            {
                selenium.Type(OwnerLocator, listSetting.Owner);   
            }
            Submit();
            string[] idStrs = selenium.GetLocation().Split('/');
            int listId = -1;
            Int32.TryParse(idStrs[idStrs.Length - 1], out listId);
            listSetting.Id = listId;
        }

        public Lists CreateList(ListSettings listSetting)
        {
            selenium.Open("/Admin/Contents/Create/List");
            InputListSetting(listSetting);               
            return new Lists(listSetting);
        }

        public Lists EditList(Lists list, ListSettings newSetting)
        {
            ContentItemHelper.DoActionToContentItem(list, ContentItemAction.Edit);
            InputListSetting(newSetting);
            return new Lists(newSetting);
        }

        public void MoveOrphanedContentItemToList(Lists list, ContentItem orphanedItem)
        {
            
            ContentItemHelper.ShowOrphanedContentItems();
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", orphanedItem.Id));
            selenium.Select("TargetContainerId", String.Format("label=List: {0}", list.Title));
            ClickAndWait("//button[@name='submit.BulkEdit']"); 
        }

        public void RemoveContentItemFromList(Lists list, ContentItem contentItem)
        {
            RemoveContentItemFromList(list, contentItem.Id.ToString());
        }

        public void RemoveContentItemFromList(Lists list, string contentItemId)
        {
            ContentItemHelper.DoActionToContentItem(list, ContentItemAction.ShowContainedItems);
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", contentItemId));
            selenium.Select("publishActions", "label=Remove from List");
            ClickAndWait("//button[@name='submit.BulkEdit']");
        }

        public void MoveContentItemFromOneListToAnother(Lists sourceContainerId, Lists targetContainerId, ContentItem contentItem)
        {
            MoveContentItemFromOneListToAnother(sourceContainerId, targetContainerId, contentItem.Id.ToString()); 
        }

        public void MoveContentItemFromOneListToAnother(Lists sourceContainerId, Lists targetContainerId, string contentItemId)
        {
            ContentItemHelper.DoActionToContentItem(sourceContainerId, ContentItemAction.ShowContainedItems);
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", contentItemId));
            selenium.Select("publishActions", "label=Move to List...");
            selenium.Select("TargetContainerId", String.Format("label=List: {0}", targetContainerId.Title));
            ClickAndWait("//button[@name='submit.BulkEdit']");
        }

        public void ChooseContentItemFromOneListToAnother(Lists fromContainerId, Lists toContainerId, ContentItem contentItem)
        {
            selenium.Open(String.Format("/Admin/Lists/Choose/From/{0}/To/{1}/Page", fromContainerId.Id, toContainerId.Id));
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", contentItem.Id));
            selenium.Select("TargetContainerId", String.Format("Move to {0}", toContainerId.Title));
            ClickAndWait("//button[@name='submit.MoveTo']");
        }

        public void ChooseContentItemFromOrphanedToAnother(Lists toContainerId, string contentItemId, bool submit)
        {
            if (!selenium.GetLocation().Contains("/Admin/Lists/Choose/From/Orphaned/To"))
            selenium.Open(String.Format("/Admin/Lists/Choose/From/Orphaned/To/{0}", toContainerId.Id));
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", contentItemId));
            selenium.Select("TargetContainerId", String.Format("Move to {0}", toContainerId.Title));
            if (submit) ClickAndWait("//button[@name='submit.MoveTo']");
        }

        public void DoSelectActionToContentItem(Lists list, string listItemTitle, ListItemAction action)
        {
            int index = GetListItemIndexOnManageContents(list,listItemTitle);
            selenium.Check(String.Format("{0}[{1}]/div/div/input", ListItemListLocator, index));
            switch (action)
            {
                case ListItemAction.Publish:
                    selenium.Select("publishActions", "label=Publish Now");
                    break;
                case ListItemAction.Unpublish:
                    selenium.Select("publishActions", "label=Unpublish");
                    break;                
                default:
                    break;
            }
            ClickAndWait("//button[@name='submit.BulkEdit']");
        }

        public void DoActionToListItem(Lists list,string listItemTitle, ListItemAction action)
        {
            int listItemIndex = GetListItemIndexOnManageContents(list,listItemTitle);
            string actionText = null;
            switch (action)
            {
                case ListItemAction.Edit:
                    actionText = "Edit";
                    break;
                case ListItemAction.Publish:
                    actionText = "Publish";
                    break;
                case ListItemAction.Delete:
                    actionText = "Delete";
                    break;
                case ListItemAction.Unpublish:
                    actionText = "Unpublish";
                    break;
                case ListItemAction.View:
                    actionText = "View";
                    break;
            }
            int actionIndex = GetActionIndexByText(listItemIndex, actionText);
            ClickAndWait(String.Format("{0}[{1}]/div/div[2]/a[{2}]", ListItemListLocator, listItemIndex, actionIndex));
        }

        private int GetActionIndexByText(int listItemIndex, string actionText)
        {
            var actionCount = (int)selenium.GetXpathCount(String.Format("{0}[{1}]/div/div[2]/a", ListItemListLocator, listItemIndex));
            for (int i = 1; i <= actionCount; i++)
            {
                if (selenium.GetText(String.Format("{0}[{1}]/div/div[2]/a[{2}]", ListItemListLocator, listItemIndex, i)) == actionText)
                {
                    return i;
                }
            }
            return 0;
        }

        private int GetListItemIndexOnManageContents(Lists list, string listItemTitle)
        {
            var count = GetListItemsCount(list);
            var index = 1;
            for (; index <= count; ++index)
            {
                string path = String.Format("{0}[{1}]/div/div/h3/a", ListItemListLocator, index);
                var text = selenium.GetText(path);
                if (String.CompareOrdinal(listItemTitle, text) == 0)
                    break;
            }

            if (index > count)
                throw new CaseFailureException(String.Format("Can't find list item {0} in this List page!", listItemTitle));

            return index;
        }

        public int GetListItemsCount(Lists list)
        {
            ManageList(list);
            return (int)selenium.GetXpathCount(ListItemListLocator);              
        }

        public ListItemStatus GetListItemStatus(Lists list, string listItemTitle)
        {
            ManageList(list);
            int index= GetListItemIndexOnManageContents(list, listItemTitle);
            if (selenium.GetText(string.Format("{0}[{1}]/div/div[2]", ListItemListLocator, index)).Contains("Unpublish"))
                return ListItemStatus.Publish;
            else return ListItemStatus.Unpublish;
        }

        private void ManageList(Lists list)
        {
            string listUrl = "/Admin/Lists/" + list.Id;
            if (!selenium.GetLocation().Contains(listUrl))
                selenium.Open(listUrl);
        }

        public bool IsListItemExist(Lists list, string listItemTitle)
        {
            ManageList(list);
            if (selenium.IsElementPresent("link=" + listItemTitle))
                return true;
            else return false;
        }

        public void FilterListAndMoveListItem(Lists list_MoveTo, string showOption_ContentType, string fromOption_ListTitle, string orderByoption,string listItemId_move,bool applyMoveTo)
        {
            selenium.Open("/Admin/Lists/Choose/From/Orphaned/To/" + list_MoveTo.Id);
            if(!string.IsNullOrEmpty(showOption_ContentType)) selenium.Select("filterResults", "label=" + showOption_ContentType);
            if (!string.IsNullOrEmpty(fromOption_ListTitle)) selenium.Select("SourceContainerId", "label=" + fromOption_ListTitle);
            if (!string.IsNullOrEmpty(orderByoption)) selenium.Select("orderResults", "label=" + orderByoption);
            selenium.Click("submit.Filter");
            System.Threading.Thread.Sleep(6000);
            if (applyMoveTo)
            {
                if(!string.IsNullOrEmpty(listItemId_move))
                    MoveListItemAfterFilter(listItemId_move);
            }
        }

        private void MoveListItemAfterFilter(string listItemId)
        {
            //input[@name='itemIds' and @value='28']
            selenium.Check(String.Format("//input[@name='itemIds' and @value='{0}']", listItemId));
            ClickAndWait("//button[@name='submit.MoveTo']");
        }

    }

    public class ListSettings : ContentItemSettings
    {  
        public OrderByProperty OrderByProperty { get; set; }

        public OrderByDirection OrderByDirection { get; set; }

        public string ItemContentType { get; set; }

        public int PageSize { get; set; }

        public bool Paginated { get; set; }

        public bool OnMainMenu { get; set; }
       
        public String MenuText { get; set; }
        
        public bool OnAdminMenu { get; set; }

        public string AdminMenuText { get; set; }

        public string AdminMenuPosition { get; set; }        

        public ListSettings()
        {
            string uniqueIdentifier = UIHelperBase.GenerateUniqueIdentifier(DateTime.Now);
            Title = String.Format("List {0}", uniqueIdentifier);
            Permalink = String.Format("list-{0}", uniqueIdentifier);
            Owner = TestLibrary.Consts.AdminUserName;
            OrderByProperty = OrderByProperty.DatePublished;
            OrderByDirection = OrderByDirection.Descending;
            PageSize = 10;
            Paginated = true;
        }       
    }

    public class Lists : ContentItem
    {
        public ListSettings ListSetting { get; private set; }

        public string MenuText { get { return ListSetting.MenuText; } }

        public Lists(ListSettings listSetting)
        {      
            ListSetting = listSetting;
            Title = listSetting.Title;
            Permalink = listSetting.Permalink;
            Owner = listSetting.Owner;
            Id = listSetting.Id;
        }
    }

    public enum OrderByProperty
    {
        DatePublished,
        Title,
        Slug,
        Custom1,
        Custom2,
        Custom3
    }

    public enum OrderByDirection
    {
        Ascending,
        Descending
    }   

    public enum ListAction
    {
        View,
        Publish,
        Unpublish,
        ShowContainedItems,
        Edit,
        Delete
    }

    public enum ListItemAction
    {
        View,
        Unpublish,
        Publish,        
        Edit,
        Delete,  
        RemoveFromList,
        MoveToList,
        NoAction
    }

    public enum ListItemStatus
    {
        Unpublish,
        Publish       
    }

    public enum ListItemOrderByOption
    {
        recentlycreated,
        recentlymodified,
        recentlypublished
    }

}
